<?php
define('BPD_SELECTALL', -1);

class BpdTable
{
/**
 * Nom de la base
 */
public $name;
/**
 * Champs de la table
 */
public $fields;
/**
 * Clés de la table
 */
public $keys;
/**
 * Prefixe des champs de cette table
 */
protected $_prefix;
/**
 * Syntaxe MySql pour le label d'un enregistrement
 */
public $label;
/**
 * Tables liées à cette table
 */
public $relto1;
/**
 * Tables liées
 */
public $relton;

/**
 * Constructeur
 */
function __construct($pname)
{
	$this->name		= $pname;
	$this->_prefix	= substr($pname,0,3).'_';
	$this->label	= '';
	$this->fields	= Array();
	$this->keys		= Array();
	$this->relto1	= Array();
	$this->relton	= Array();
}

/**
 * Ajout d'un champ
 */
function AddField($pfield, $pkey=False)
{
	$this->fields[$pfield->name] = $pfield;
	if ($pkey){
		$this->keys[$pfield->name] = $pfield;
	}
	$pfield->prefix = $this->_prefix;
	$pfield->table = $this->name;
}

/**
 * Ajout d'une relation To1
 * un enregistement de cette table est lié a UN enregistement de l'autre
 */
function AddRelTo1($ptable)
{
	$this->relto1[] = $ptable;
	foreach ($ptable->keys as $key) {
		$field = clone $key;
		$field->name = $ptable->_prefix.$field->name;
		$field->sql = $field->name;
		$this->AddField($field);
	}
	$ptable->AddRelToN($this);
}

/**
 * Ajout d'une relation To1
 * un enregistement de cette table est lié a plusieurs enregistements de l'autre
 */
function AddRelToN($ptable)
{
	$this->relto1n[] = $ptable;
}

/**
 * Definition de la syntaxe du label
 */
function SetLabel($plabel)
{
	$field = new BpdField('label', VARCHAR);
	$field->prefix = $this->_prefix;
	$field->sql = $plabel;
	$this->AddField($field);
}

/**
 * Obtention de la requete
 */
function Select($pfields=BPD_SELECTALL,$pkeys=Array(), $poffset = -1, $pnb = -1)
{
	// Calcul du SELECT
	if ( $pfields == -1 )
		$fields = $this->fields;
	else {
		$fields = Array();
		foreach($pfields as $pfield){
			$fields[$pfield] = $this->fields[$pfield];
		}
	}
	foreach($fields as $field){
		$strfields[] = $field->GetSql();
	}
	$strfields = implode(', ', $strfields);
	// Calcul du WHERE
	$where = '';
	if (count($pkeys)>0) {
		$wheres = Array();
		$i = 0;
		foreach ($this->keys as $name=>$field){
			if ( isset($pkeys[$i]) )
				$wheres[] = $field->GetSql().'='.$pkeys[$i];
			$i++;
		}
		$where = ' WHERE '.implode(' AND ', $wheres);
	}
	// Calcul du LIMIT
	$limit = '';
	if ($poffset != -1) {
		if ($pnb == -1)
			$limit = " LIMIT $poffset";
		else
			$limit = " LIMIT $poffset, $pnb";
		}
	return "SELECT $strfields FROM {$this->name}$where$limit";
}

function SelectAll($pfields=BPD_SELECTALL, $poffset = -1, $pnb = -1)
{
}

function SelectRelToN()
{
}
}// class BpdTable
?>
